<template>
  <div >
    <el-breadcrumb style="margin-bottom: 10px" separator="/" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/admin/article/list">文章管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>文章列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--查询or添加-->
    <el-form v-show="showSearch"  :rules="rules" :inline="true" ref="form" :model="params" label-width="68px">

      <el-form-item label="文章名称">
        <el-input style="width: 150px" size="small" v-model="params.title"   placeholder="请输入文章名称"/>
      </el-form-item>
      <el-form-item label="标签名">
        <el-select style="width: 130px" size="small" v-model="params.tagId" placeholder="请选择标签">
          <el-option v-for="item in tags" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>

      <el-form-item label="分类名">
<!--        filterable clearable reserve-keyword-->
        <el-select style="width: 130px" size="small" v-model="params.categoryId" placeholder="请选择分类">
          <el-option v-for="item in categoryArr" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>

      <el-form-item label="发布状态">
        <el-select style="width: 130px" size="small" v-model="params.status"
                   placeholder="是否发布" >
          <el-option v-for="(item,index) in publishList" :key="index" :label="item" :value="index"/>
        </el-select>
      </el-form-item>
      <el-form-item>

        <el-button type="primary" icon="el-icon-search" size="small" @click="handleFind">查找</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
        <el-button type="primary"  size="mini"   @click="handleDeleteList()">批量删除</el-button>
      </el-form-item>
    </el-form>
    <el-table
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectChange"
    >
      <el-table-column
          type="selection"
          width="50">
      </el-table-column>
<!--      <el-table-column prop="id" label="id" width="50"></el-table-column>-->
      <el-table-column  prop="viewPicture" label="文章封面" width="120">
        <template slot-scope="scope">
        <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.viewPicture"
            ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" width="150"></el-table-column>
      <el-table-column prop="isOriginal" label="类型" width="60"></el-table-column>
      <el-table-column prop="categoryName" label="分类" width="100"></el-table-column>
      <el-table-column prop="tagName"  label="标签" width="200">
        <template slot-scope="scope">
        <el-tag
            style="margin-left: 3px"
            align="center"
            type="primary"
            v-for="(item) in strSplit(scope.row.tagName)"
        >{{item}}
        </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否推荐" prop="isRecommended"   width="100">
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.isRecommended"
              @change="handleEditRecommon(scope.$index, scope.row.id, scope.row.isRecommended)"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#999">
          </el-switch>
        </template>
      </el-table-column>
<!--      <el-table-column prop="isRecommended" label="是否推荐" width="80"></el-table-column>-->
      <el-table-column prop="viewCount" label="浏览量" width="80"></el-table-column>
      <el-table-column prop="gmtCreate" label="发表时间" width="150"></el-table-column>
      <el-table-column label="操作" width="200px">
        <template slot-scope="scope">
          <el-button icon="el-icon-search" @click="cardPopup(scope.row)" circle></el-button>
          <el-button type="primary" icon="el-icon-edit"  @click="dialogVisible=true;selectById(scope.row.id)" circle></el-button>
          <el-button type="danger" icon="el-icon-delete" @click="openDeleteConfirm(scope.row.id)" circle></el-button>
        </template>
      </el-table-column >



    </el-table>


    <!--分页区域-->
    <div class="pagination-container" style="float: right;margin-bottom: 1.25rem;margin-top: 1.25rem;">
      <el-pagination background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="pageNo"
                     :page-size="pageSize"
                     :page-sizes="[2,10, 20, 30]"
                     layout="total, sizes,prev, pager, next,jumper"
                     :total="total">
      </el-pagination>
    </div>

<!--  编辑框  -->

    <el-dialog
        title="编辑文章"
        append-to-body
        :visible.sync="dialogVisible"
        width="50%"
        height="100%"
        >
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="180px" class="demo-ruleForm">
        <el-form-item  label="标题" prop="title">
          <el-input readonly="true" v-model="ruleForm.title" maxlength="15" show-word-limit clearable
                    style="width: 300px;"></el-input>
        </el-form-item>

        <el-form-item  label="分类" prop="categoryName">
          <el-input readonly="true" v-model="ruleForm.categoryName" maxlength="15" show-word-limit clearable
                    style="width: 300px;"></el-input>
        </el-form-item>


        <el-form-item  label="排序" prop="sort">
          <el-input  v-model="ruleForm.sort"  show-word-limit clearable
                    style="width: 300px;"></el-input>
        </el-form-item>

      </el-form>
      <div   style="margin: 0 0 10px 200px;">
        <h3 style="margin-bottom: 10px">文章标签</h3>
      <el-tag
          :key="tag"
          v-for="tag in this.ruleForm.tags"
          closable
          :disable-transitions="false"
          >
        {{tag}}
      </el-tag>


      </div>


        <el-button   style="position:relative;left:200px" @click="dialogVisible = false">取 消</el-button>
    <el-button style="position:relative;left:200px"  type="primary" @click="dialogVisible = false;updateArticles()">确 定</el-button>

    </el-dialog>


<!--  查询文章详情  -->
    <template>
      <el-dialog
          title="文章详情"
          append-to-body
          :visible.sync="dialogVisible1"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          width="65%"
          @close="closeDialog('ruleForm')">
        <div>
          <mavon-editor
              class="md"
              :value="content"
              :subfield="false"
              :defaultOpen="'preview'"
              :toolbarsFlag="false"
              :editable="false"
              :scrollStyle="true"
              :ishljs="true"
          />
        </div>
      </el-dialog>
    </template>

    </div>

</template>


<script>



export default {
  data() {
    return {
      ruleForm: {
        id: '',
        title:"",
        categoryName: '',
        tagId: 0,
        categoryId:0,
        tags:[],
        tagName:'',
        content:"",
        sort:0,
        examineStatus:'',
      },
      dialogVisible:false,
      /*查询文章内容的显示*/
      dialogVisible1:false,
      pageNo: 1,
      pageSize: 10,
      /*表单判断条件*/
      showSearch: true,
      /*是否被推荐*/
      // isRecommended:0,
      tags:[],
      categoryArr:[],
      /*文章列表数据*/
      tableData: [],
      /*复选框数组*/
      multipleSelection: [],
      publishList: ['下架','待发布', '发布'],
      /*当前也数量*/
      total: 0,
      /*文章查询总数*/
      count:0,
      tagName:'',
      /*标签编辑框变量*/
      inputVisible:true,
      inputValue:'' ,
      rules:
          {
            'title': [{required: true,message: '必填字段',trigger: 'blur'}],
          },

      params: {
        title: null,
        tagId: null,
        categoryId: null,
        status: null,
        offset:1,
        count:10
      },
      roleStatus:'待审核'
    }
  },
  created:function () {
    //请求所有分类数据
    let url='http://localhost:9090/system/category'
    console.log("url="+url)
    this.axios.get(url).then( (response)=> {
      this.categoryArr = response.data.data;
      console.log(this.params.categoryArr)
    })

    //请求所有标签数据
    url='http://localhost:9090/tags/select'
    console.log("url="+url)
    this.axios.get(url).then( (response)=> {
      this.tags = response.data.data;
    })

    /*文章列表*/
    this.queryList();
  },
  methods: {
      /*查看文章内容*/
    cardPopup(row) {
      this.content = row.content;
      this.dialogVisible1 = true;              // 打开弹窗
    },
    closeDialog(ruleForm) {
      if (this.$refs[ruleForm] !== undefined) {
        this.$refs[ruleForm].resetFields();
      }
    },
    updateArticles:function(){
        let url ='http://localhost:9090/system/articles/'+this.ruleForm.id+'/update'
        let data={
       sort:this.ruleForm.sort
      }
      this.axios.post(url,data).then((response)=>{
        switch (response.data.code) {
          case 20000:
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
            this.queryList()
            break;
          default:
            this.$message({
              type: 'error',
              message: '修改失败!'
            });
            break;
        }
      })
    },
    /*通过id查询*/
    selectById:function (id) {
      let url ='http://localhost:9090/system/articles/selectById?id='+id
      this.axios.get(url).then( (response)=> {
       console.log(response)
        this.ruleForm=response.data.data;
       if(this.ruleForm.tagName!=null&&this.ruleForm.tagName!=''){
          this.ruleForm.tags=this.ruleForm.tagName.split(",")
       }
      })
    },

    /*划分标签*/
    strSplit: function (item) {
      if(item==null||item==""){
        return
      }
      return item .split(",")
    },

    queryList:function () {

      /*查询文章数量*/
      let url = 'http://localhost:9090/system/articles/selectCount';
      this.axios.post(url, this.params).then((response) => {
        this.total = response.data.data;

        // let tem =this.total
        // if (response.data.data>0){
        //   let tempPageNum = tem%this.pageSize==0?tem/this.pageSize:tem/this.pageSize+1;
        //   if(this.pageSize>tempPageNum){
        //       this.params.offset=0;
        //       this.pageSize=1;
        //
        //   }
        // }
        /*文章列表*/
        url = 'http://localhost:9090/system/articles/adminSelectFind'
        console.log("url=" + url)
        this.params.offset = (this.pageNo - 1) * this.pageSize
        this.params.count = this.pageSize

        this.axios.post(url, this.params).then((response) => {
          console.log(response)
          this.tableData = response.data.data;
          console.log('this.tableData=' + this.tableData)

        })
        // alert("页码："+this.pageNo+"，总条数："+this.total+"，每页："+this.pageSize)
        // if(this.pageNo>((this.total%this.pageSize)===0?this.total/this.pageSize:this.total/this.pageSize+1)){
        //   this.pageNo=1;
        //   alert("修改后页码："+this.pageNo+"，总条数："+this.total+"，每页："+this.pageSize)
        // }
    })
    },

    handleEditRecommon(row, id, isRecommended){

      let data = {
        id: id,
        isRecommended: isRecommended
      }
      let url = 'http://localhost:9090/system/articles/' + data.id + '/update'
      this.axios.post(url, data).then((response) => {

      })
    },

    /**
     * 复选框
     * @param val
     */
    handleSelectChange(val) {
      this.multipleSelection = val;
    },
    /*批量删除*/
    handleDeleteList(){
      if (this.multipleSelection.length < 1) {
        this.$message({
          type: 'warning',
          message: '请勾选需要删除的品牌'
        });
        return;
      }
      let array = [];
      for (let i = 0; i < this.multipleSelection.length; i++) {
        array.push(this.multipleSelection[i].id);
      }
      console.log("需要删除的id:" + array)
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.post("http://localhost:9090/system/articles/deleteByIds", array).then((response) => {
          switch (response.data.code) {
            case 20000:
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.queryList()
              break;
            default:
              this.$message({
                type: 'error',
                message: '删除失败!'
              });
              break;
          }
        })
      }).catch(() => {
        this.$refs.multipleTable.clearSelection();
        this.$message({
          type: 'info',
          message: '已取消批量删除'
        });
      });
    },
    /*分页查询，页码变化*/
    handleSizeChange: function (val) {
      this.pageSize = val
      this.queryList();

    },
    handleCurrentChange: function (val) {

      //当前页码
      this.pageNo = val
      this.queryList();
    },
    /*根据id删除文章*/
    openDeleteConfirm(id){
      let url='http://localhost:9090/system/articles/'+id+'/delete'
      this.axios.post(url).then((response)=> {
        if(response.data.code==20000){
          this.$message({
            message:'删除文章成功！',
            type:'success'
          });
        }
        this.queryList();
      }).catch(function (error) {
        console.log("响应失败！！！")
      });
    },

    /**
     * 查询全部状态账户
     */
    queryStatus(id) {
      switch (id) {
        case 1:
          this.roleStatus = '待审核';
          this.params.examineStatus = 1;
          break;
        case 2:
          this.roleStatus = '审核通过';
          this.params.examineStatus = 2;
          break;
        case 3:
          this.roleStatus = '审核失败';
          this.params.examineStatus = 3;
          break;
        case 4:
          this.roleStatus = '全部状态';
          this.params.examineStatus = null;
          break;
      }
      this.listRoleByCondition();
    },

    /**/
    handleFind(){
      this.queryList();
    },
    resetQuery: function (){
          this.params.title=null,
          this.params.tagId=null,
          this.params.categoryId=null,
          this.params.status=null,
      this.queryList()
    },
  }
}
</script>
<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>